Topics we’ll cover today

  • Quick recap from first workshop
  • What does tidy data look like?
  • What’s the pipe?
  • Renaming variables, rearranging data
  • Subsetting data
  • Merge and split columns

Unless indicated, artwork is by the wonderful @allison_horst - find her on github.

(0) Recap

R-Studio

…is an integrated development environment (IDE) for R which adds lots of useful features

Layout

Top-left: scripting panel – write and save code
Bottom-left: console panel
Top-right: environment panel – shows dataframes, variables…
Bottom-right: install and update packages, preview plots, read help files

R-Markdown

file extension: .Rmd
- text interpreted as plain text
- code needs to be in a code chunk such as this one:

  • add by either typing or by clicking on “Insert” at the top of this pane, then choose R
  • run a line using the Run button at the top or Ctrl/Cmd + Enter
  • run an entire chunk by clicking on the green triangle on its right
  • add a hashtag do designate something as a comment: R will ignore any line that starts with #
2 + 7
## [1] 9
# don't do anything
1 - 9
## [1] -8

Variables

Assign value(s) to a label, e.g.

num_cats <- 8
fav_numbers <- c(8, 14, 2)

The c() syntax is necessary for the second example because we have multiple items, so they need to be inside a vector.

We can now work with these variables. Mathematical operations are “broadcast”, i.e. applied, to each item in a vector.

fav_numbers - num_cats
## [1]  0  6 -6

Data types

  • numeric: numbers (can include decimals)
  • integer: whole numbers, without decimals
  • character: text (needs to be in quotation marks)
  • logical: can only be TRUE or FALSE (useful for comparing data)
  • factor: category labels

Check which data type something is by using class:

class(3)
## [1] "numeric"
class("hi there")
## [1] "character"
class(TRUE)
## [1] "logical"

Data types can be changed, e.g. 

as.integer(4.8)
## [1] 4

Packages

Packages extend base-R functionality by adding more specialised commands. The first time you use a new package, you need to install it using install.packages("packagename"). Afterwards, it needs to be loaded - with library(packagename) - every time you open RStudio. If you didn’t last time, install the cowsay package (remove the hashtag to uncomment the line before running them) and load it:

#install.packages("cowsay")

library(cowsay)

Reading in data

Reading in data tends to follow this pattern (note that these commands require the tidyverse packages to be installed and loaded):

name_of_data_in_R <- read_csv("data_file.csv") # equivalent to
name_of_data_in_R <- read_delim("data_file.csv", delim = ",")

name_of_data_in_R <- read_csv2("data_file.csv") # equivalent to
name_of_data_in_R <- read_delim("data_file.csv", delim = ";")

name_of_data_in_R <- read_tsv("data_file.txt") # tab-separated file

This works as long as the data file is saved in the same location as this file! You can add e.g. “data/” before the file name if it is located in a subfolder.

Communicating with R

Understanding warnings and errors

R will often “talk” to you when you’re running code. For example, when you install a package, it’ll tell you e.g. where it is downloading a package from, and when it’s done. Similarly, when you loaded the tidyverse collection of packages, R listed them all. That’s nothing to worry about!

When there’s a mistake in the code (e.g. misspelling a variable name, forgetting to close quotation marks or brackets), R will give an error and be unable to run the line. The error message will give you important information about what went wrong.

hello <- "hi"
#Hello

In contrast, warnings are shown when R thinks there could be an issue with your code or input, but it still runs the line. R is generally just telling you that you MIGHT be making a logical error, not that the code is impossible.

c(1, 2, 3) + c(1, 2)
## Warning in c(1, 2, 3) + c(1, 2): longer object length is not a multiple of
## shorter object length
## [1] 2 4 4

It’s normal that you’ll encounter both warnings and errors while coding! This debugging (= finding and fixing errors in code) bingo gives a few suggestions of what might have gone wrong.

Debugging bingo, by Dr Ji Son, @cogscimom on Twitter

Reading function documentation

We’ll get to know a number of R functions today. These functions can take one or more arguments. As an example, let’s try out the say() function from the cowsay package.

First, (install and) load the cowsay package:

# install.packages("cowsay")
library(cowsay)

Try the following code:

say(
  what = "Good luck learning about the tidyverse!", 
  by = "rabbit")
## 
##  ----- 
## Good luck learning about the tidyverse! 
##  ------ 
##     \   
##      \
##       ( )_( )
##       (='.'=)
##       (^)_(^) [nosig]
## 

We can see that this function has the what argument (what should be said?) and the by argument (which animal should say it?). But what other options are there for this command - which other animals, for example, or can you change the colour? To see the documentation for the say command, you can either run this line of code:

?say

…or type in say in the Help tab on the bottom right.

This will show you the documentation for the command.

  • Usage shows an overview of the function arguments and their defaults (e.g. if you typed in say() without any arguments in the brackets, you’d get the defaults, i.e. a cat saying “Hello world!”)
say()
## 
##  -------------- 
## Hello world! 
##  --------------
##     \
##       \
##         \
##             |\___/|
##           ==) ^Y^ (==
##             \  ^  /
##              )=*=(
##             /     \
##             |     |
##            /| | | |\
##            \| | |_|/\
##       jgs  //_// ___/
##                \_)
## 
  • Arguments provides more information on each argument. Arguments are the options you can use within a function.

  • what

  • by

  • type

  • what_color etc. Each of these can be fed the say() function to slightly alter what it does.

  • Examples at the bottom of the help page lists a few examples you can copy-paste into your code to better understand how a function works.

Don’t worry if you don’t understand everything in the documentation when you’re first starting out. Just try to get an idea for which arguments there are and which options for those arguments. It’s good practice to look at help documents often – this will also help you get more efficient at extracting the info you need from them.

(1) Welcome to the tidyverse

Welcome to the tidyverse! Tidyverse is a package – really, a whole collection of packages – that include a LOT of useful functions for all sorts of data analyzing, cleaning and “wrangling”. They all share “an underlying design philosophy, grammar, and data structures”, according to the tidyverse website. In other words, its commands/functions all have a similar structure and descriptive names to make them easier to remember and use.

The tidyverse

To start, make sure you have tidyverse installed. You can do this either through the panel at the lower left hand corner (Packages tab) or by typing into the Console install.packages("tidyverse"). Then, call the tidyverse with a library() call and let’s get started!

library(tidyverse)
## ── Attaching packages ────────────────────────────────────────────────────────────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.3     ✓ dplyr   1.0.0
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ───────────────────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

Tidyverse loads multiple key packages: - dplyr -> for all sorts of data transformation and wrangling - ggplot2 -> the best plotting package in R (and ever??) - readr & tibble -> for reading in files to tibble format (improvements over R base data.frames) - stringr -> for text transformations (removing trailing whitespaces, etc.) - magrittr -> for pipes, more on this below

It also loads purr (for vectorized programming), forcats (improvements to factors), readxl (for reading Excel documents), lubridate (for working with dates/times) and more.

Tidy data

Characteristics of tidy data:

What does tidy data look like?

Why this format?
- a lot of wrangling commands are based on the assumption that your data is tidy - the format is expected for many statistical models - tidy data works best for plotting - “Tidy datasets are all alike, but every messy dataset is messy in its own way” (Hadley Wickham)

Why use tidy data?

(2) The pipe %>%

  • One of the most noticeable features of the tidyverse: the pipe %>% (keyboard shortcut: Ctr/Cmd + Shift + M)

  • Takes the item before it and feeds it to the following command as the first argument

    • All tidyverse (and some non-tidyverse) functions take the dataframe as the first function
    • Can be used to string commands

Load in the following dataset, which contains IKEA furniture items in Saudi Arabia and their prices (in Saudi Riyals)

ikea <- read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-11-03/ikea.csv')
## Warning: Missing column names filled in: 'X1' [1]
## Parsed with column specification:
## cols(
##   X1 = col_double(),
##   item_id = col_double(),
##   name = col_character(),
##   category = col_character(),
##   price = col_double(),
##   old_price = col_character(),
##   sellable_online = col_logical(),
##   link = col_character(),
##   other_colors = col_character(),
##   short_description = col_character(),
##   designer = col_character(),
##   depth = col_double(),
##   height = col_double(),
##   width = col_double()
## )

This dataset has some NAs so we’ll quickly remove them with drop_na. Note: This is an online dataset, where the NAs are meaningless, and we’re not preparing any sophisticated analysis. If this were your own data, you should think about what the NAs represent and if you can replace them in another way. drop_na() will drop the WHOLE ROW if there is an NA in any of the columns.

ikea <- drop_na(ikea)

First, take a look at the dataset. You can do this with head(ikea) or try out using the pipe.

head(ikea)
## # A tibble: 6 x 14
##      X1 item_id name  category price old_price sellable_online link 
##   <dbl>   <dbl> <chr> <chr>    <dbl> <chr>     <lgl>           <chr>
## 1     3  8.02e7 STIG  Bar fur…    69 No old p… TRUE            http…
## 2     4  3.02e7 NORB… Bar fur…   225 No old p… TRUE            http…
## 3     5  1.01e7 INGO… Bar fur…   345 No old p… TRUE            http…
## 4     6  7.04e7 FRAN… Bar fur…   129 No old p… TRUE            http…
## 5     8  5.04e7 FRAN… Bar fur…   129 No old p… TRUE            http…
## 6    10  9.04e7 FRAN… Bar fur…   149 No old p… TRUE            http…
## # … with 6 more variables: other_colors <chr>, short_description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>
# is equivalent to:
ikea %>% 
  head()
## # A tibble: 6 x 14
##      X1 item_id name  category price old_price sellable_online link 
##   <dbl>   <dbl> <chr> <chr>    <dbl> <chr>     <lgl>           <chr>
## 1     3  8.02e7 STIG  Bar fur…    69 No old p… TRUE            http…
## 2     4  3.02e7 NORB… Bar fur…   225 No old p… TRUE            http…
## 3     5  1.01e7 INGO… Bar fur…   345 No old p… TRUE            http…
## 4     6  7.04e7 FRAN… Bar fur…   129 No old p… TRUE            http…
## 5     8  5.04e7 FRAN… Bar fur…   129 No old p… TRUE            http…
## 6    10  9.04e7 FRAN… Bar fur…   149 No old p… TRUE            http…
## # … with 6 more variables: other_colors <chr>, short_description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>

You see that this produces the exact same output as head(ikea). Why would this be useful?

Compare the following lines of pseudocode (courtesy of @andrewheiss), which would produce the same output: Pipe as explained by Andrew Heiss

You can see that the version with the pipe is easier to read when more than one function is called on the same dataframe! In a chain of commands like this one, you can think of the pipe as meaning “and then”.

Maybe @hadleywickham’s version of a typical morning speaks more to your own experience (it certainly does for us): I %>% tumble(out_of = “bed”) %>% stumble(to = “the kitchen”) %>% pour(who = “myself”, unit = “cup”, what = “ambition”) %>% yawn() %>% stretch() %>% try(come_to_live())

As you can see in the examples, pipes work with additional arguments. Here’s how it looks for our actual data:

head(ikea, n = 2)
## # A tibble: 2 x 14
##      X1 item_id name  category price old_price sellable_online link 
##   <dbl>   <dbl> <chr> <chr>    <dbl> <chr>     <lgl>           <chr>
## 1     3  8.02e7 STIG  Bar fur…    69 No old p… TRUE            http…
## 2     4  3.02e7 NORB… Bar fur…   225 No old p… TRUE            http…
## # … with 6 more variables: other_colors <chr>, short_description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>
# is equivalent to:
ikea %>% 
  head(n = 2)
## # A tibble: 2 x 14
##      X1 item_id name  category price old_price sellable_online link 
##   <dbl>   <dbl> <chr> <chr>    <dbl> <chr>     <lgl>           <chr>
## 1     3  8.02e7 STIG  Bar fur…    69 No old p… TRUE            http…
## 2     4  3.02e7 NORB… Bar fur…   225 No old p… TRUE            http…
## # … with 6 more variables: other_colors <chr>, short_description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Try it out

We’ll use data on three species of penguins observed near Palmer Station, Antarctica. Penguins

Load this data:

penguins <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-07-28/penguins.csv')
## Parsed with column specification:
## cols(
##   species = col_character(),
##   island = col_character(),
##   bill_length_mm = col_double(),
##   bill_depth_mm = col_double(),
##   flipper_length_mm = col_double(),
##   body_mass_g = col_double(),
##   sex = col_character(),
##   year = col_double()
## )

To remind yourself of the data exploration commands we tried last workshop, try to run the following commands on the dataframe - first, in the way we showed you last time, and then using the pipe. - summary()
- colnames() - tail() - also try the n = argument

Bills, explained

(3) Renaming and rearranging data

rename()

You can rename columns with the rename() function. The syntax is new_name = old_name.

ikea %>% 
  rename(price_sar = price)
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1     3  8.02e7 STIG  Bar fur…        69 No old p… TRUE            http…
##  2     4  3.02e7 NORB… Bar fur…       225 No old p… TRUE            http…
##  3     5  1.01e7 INGO… Bar fur…       345 No old p… TRUE            http…
##  4     6  7.04e7 FRAN… Bar fur…       129 No old p… TRUE            http…
##  5     8  5.04e7 FRAN… Bar fur…       129 No old p… TRUE            http…
##  6    10  9.04e7 FRAN… Bar fur…       149 No old p… TRUE            http…
##  7    11  1.22e5 INGO… Bar fur…       395 No old p… TRUE            http…
##  8    12  3.98e5 NORR… Bar fur…       395 No old p… TRUE            http…
##  9    13  5.04e7 FREK… Bar fur…       177 SR 295    TRUE            http…
## 10    14  4.01e5 EKED… Bar fur…       345 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   short_description <chr>, designer <chr>, depth <dbl>, height <dbl>,
## #   width <dbl>

You can also rename multiple columns at once (no need for an array here):

ikea %>% 
  rename(price_sar = price, 
         description = short_description)
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1     3  8.02e7 STIG  Bar fur…        69 No old p… TRUE            http…
##  2     4  3.02e7 NORB… Bar fur…       225 No old p… TRUE            http…
##  3     5  1.01e7 INGO… Bar fur…       345 No old p… TRUE            http…
##  4     6  7.04e7 FRAN… Bar fur…       129 No old p… TRUE            http…
##  5     8  5.04e7 FRAN… Bar fur…       129 No old p… TRUE            http…
##  6    10  9.04e7 FRAN… Bar fur…       149 No old p… TRUE            http…
##  7    11  1.22e5 INGO… Bar fur…       395 No old p… TRUE            http…
##  8    12  3.98e5 NORR… Bar fur…       395 No old p… TRUE            http…
##  9    13  5.04e7 FREK… Bar fur…       177 SR 295    TRUE            http…
## 10    14  4.01e5 EKED… Bar fur…       345 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Preview vs. saving

In the first code block in this section, we’ve first previewed how changing variable names works. If you look at the ikea dataframe, for example in the Environment panel on the upper-right, the dataframe hasn’t changed. To save your changes, assign your call back to the variable name, i.e. df <- df %>% some operations here This is what we’re doing in the second code block, where we permanently change “price” to “price_sar” and “short description” to “description”.

There is also a trick to show a preview and save it to the variable – wrapping the whole call in parentheses – use with caution!

(ikea <- ikea %>% 
  rename(price_sar = price, 
         description = short_description))
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1     3  8.02e7 STIG  Bar fur…        69 No old p… TRUE            http…
##  2     4  3.02e7 NORB… Bar fur…       225 No old p… TRUE            http…
##  3     5  1.01e7 INGO… Bar fur…       345 No old p… TRUE            http…
##  4     6  7.04e7 FRAN… Bar fur…       129 No old p… TRUE            http…
##  5     8  5.04e7 FRAN… Bar fur…       129 No old p… TRUE            http…
##  6    10  9.04e7 FRAN… Bar fur…       149 No old p… TRUE            http…
##  7    11  1.22e5 INGO… Bar fur…       395 No old p… TRUE            http…
##  8    12  3.98e5 NORR… Bar fur…       395 No old p… TRUE            http…
##  9    13  5.04e7 FREK… Bar fur…       177 SR 295    TRUE            http…
## 10    14  4.01e5 EKED… Bar fur…       345 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

If you make a mistake: arrow with a line under it in the code block of R-Markdown, runs all blocks above (but not the current one). A good workflow is to try commands without saving the changes first, then, once you’re happy with the output, save the changes and overwrite the dataframe.

relocate()

Relocate

The relocate function lets you change the order of variables in the data. The following command moves the category and name columns to the beginning:

ikea %>% 
  relocate(category, name)
## # A tibble: 1,899 x 14
##    category name     X1 item_id price_sar old_price sellable_online link 
##    <chr>    <chr> <dbl>   <dbl>     <dbl> <chr>     <lgl>           <chr>
##  1 Bar fur… STIG      3  8.02e7        69 No old p… TRUE            http…
##  2 Bar fur… NORB…     4  3.02e7       225 No old p… TRUE            http…
##  3 Bar fur… INGO…     5  1.01e7       345 No old p… TRUE            http…
##  4 Bar fur… FRAN…     6  7.04e7       129 No old p… TRUE            http…
##  5 Bar fur… FRAN…     8  5.04e7       129 No old p… TRUE            http…
##  6 Bar fur… FRAN…    10  9.04e7       149 No old p… TRUE            http…
##  7 Bar fur… INGO…    11  1.22e5       395 No old p… TRUE            http…
##  8 Bar fur… NORR…    12  3.98e5       395 No old p… TRUE            http…
##  9 Bar fur… FREK…    13  5.04e7       177 SR 295    TRUE            http…
## 10 Bar fur… EKED…    14  4.01e5       345 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

You can also specify that a variable should be placed before or after another variable:

ikea %>% 
  relocate(item_id, .after = name)
## # A tibble: 1,899 x 14
##       X1 name  item_id category price_sar old_price sellable_online link 
##    <dbl> <chr>   <dbl> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1     3 STIG   8.02e7 Bar fur…        69 No old p… TRUE            http…
##  2     4 NORB…  3.02e7 Bar fur…       225 No old p… TRUE            http…
##  3     5 INGO…  1.01e7 Bar fur…       345 No old p… TRUE            http…
##  4     6 FRAN…  7.04e7 Bar fur…       129 No old p… TRUE            http…
##  5     8 FRAN…  5.04e7 Bar fur…       129 No old p… TRUE            http…
##  6    10 FRAN…  9.04e7 Bar fur…       149 No old p… TRUE            http…
##  7    11 INGO…  1.22e5 Bar fur…       395 No old p… TRUE            http…
##  8    12 NORR…  3.98e5 Bar fur…       395 No old p… TRUE            http…
##  9    13 FREK…  5.04e7 Bar fur…       177 SR 295    TRUE            http…
## 10    14 EKED…  4.01e5 Bar fur…       345 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Another option is to sort by data type using where():

ikea %>% 
  relocate(where(is.character))
## # A tibble: 1,899 x 14
##    name  category old_price link  other_colors description designer    X1
##    <chr> <chr>    <chr>     <chr> <chr>        <chr>       <chr>    <dbl>
##  1 STIG  Bar fur… No old p… http… Yes          Bar stool … Henrik …     3
##  2 NORB… Bar fur… No old p… http… No           Wall-mount… Marcus …     4
##  3 INGO… Bar fur… No old p… http… No           Bar stool … Carina …     5
##  4 FRAN… Bar fur… No old p… http… No           Bar stool … K Hagbe…     6
##  5 FRAN… Bar fur… No old p… http… No           Bar stool … K Hagbe…     8
##  6 FRAN… Bar fur… No old p… http… No           Bar stool … K Hagbe…    10
##  7 INGO… Bar fur… No old p… http… No           Bar stool … Carina …    11
##  8 NORR… Bar fur… No old p… http… No           Bar stool … Nike Ka…    12
##  9 FREK… Bar fur… SR 295    http… No           Bar stool … Nichola…    13
## 10 EKED… Bar fur… No old p… http… No           Bar stool … Ehlén J…    14
## # … with 1,889 more rows, and 6 more variables: item_id <dbl>, price_sar <dbl>,
## #   sellable_online <lgl>, depth <dbl>, height <dbl>, width <dbl>
ikea %>% 
  relocate(where(is.numeric))
## # A tibble: 1,899 x 14
##       X1 item_id price_sar depth height width name  category old_price
##    <dbl>   <dbl>     <dbl> <dbl>  <dbl> <dbl> <chr> <chr>    <chr>    
##  1     3  8.02e7        69    50    100    60 STIG  Bar fur… No old p…
##  2     4  3.02e7       225    60     43    74 NORB… Bar fur… No old p…
##  3     5  1.01e7       345    45     91    40 INGO… Bar fur… No old p…
##  4     6  7.04e7       129    44     95    50 FRAN… Bar fur… No old p…
##  5     8  5.04e7       129    44     95    50 FRAN… Bar fur… No old p…
##  6    10  9.04e7       149    44    103    52 FRAN… Bar fur… No old p…
##  7    11  1.22e5       395    45    102    40 INGO… Bar fur… No old p…
##  8    12  3.98e5       395    47    103    46 NORR… Bar fur… No old p…
##  9    13  5.04e7       177    53    104    43 FREK… Bar fur… SR 295   
## 10    14  4.01e5       345    52    114    43 EKED… Bar fur… No old p…
## # … with 1,889 more rows, and 5 more variables: sellable_online <lgl>,
## #   link <chr>, other_colors <chr>, description <chr>, designer <chr>

Reordering variables is particularly useful if you have large datasets with lots of variables.

arrange()

Let’s say we want to sort the items by price quickly, to get an idea for the most and least expensive items. For this, we can use arrange()

By default, this shows the items from lowest to highest:

ikea %>% 
  arrange(price_sar)
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1   461  3.36e5 SKÅD… Bookcas…         6 SR 10/4 … TRUE            http…
##  2  1839  4.05e7 TROF… Childre…        10 No old p… FALSE           http…
##  3  1946  4.05e7 TROF… Nursery…        10 No old p… FALSE           http…
##  4  2718  2.03e7 ISBE… Tables …        10 No old p… TRUE            http…
##  5   325  6.04e7 JONA… Bookcas…        15 No old p… TRUE            http…
##  6   379  5.03e7 BROR  Bookcas…        15 No old p… TRUE            http…
##  7   616  3.40e5 EKET  Bookcas…        15 No old p… TRUE            http…
##  8  1212  6.02e7 FÖRS… Chairs          15 No old p… TRUE            http…
##  9  1742  6.02e7 FÖRS… Childre…        15 No old p… TRUE            http…
## 10  1848  3.05e7 TROF… Childre…        15 No old p… FALSE           http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

But you can also arrange the prices from highest to lowest by wrapping the column name in desc()

ikea %>% 
  arrange(desc(price_sar))
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1   190  2.93e7 LIDH… Beds          9585 No old p… TRUE            http…
##  2  2344  7.93e7 LIDH… Sofas &…      9585 No old p… TRUE            http…
##  3  2559  8.93e7 GRÖN… Sofas &…      8900 No old p… TRUE            http…
##  4  2387  6.93e7 VIMLE Sofas &…      8395 No old p… TRUE            http…
##  5  2289  5.92e7 KIVIK Sofas &…      8295 No old p… TRUE            http…
##  6  2445  9.93e7 LIDH… Sofas &…      8240 No old p… TRUE            http…
##  7   251  5.93e7 LIDH… Beds          7873 SR 9,430  TRUE            http…
##  8  2589  5.93e7 LIDH… Sofas &…      7873 SR 9,430  TRUE            http…
##  9   214  2.93e7 LIDH… Beds          7785 No old p… TRUE            http…
## 10  2397  2.93e7 LIDH… Sofas &…      7785 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Or in alphabetical order if the column is a character type:

ikea %>% 
  arrange(name)
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1  1136  1.02e7 ADDE  Chairs          40 No old p… TRUE            http…
##  2  1343  7.03e7 AGAM  Chairs         195 No old p… TRUE            http…
##  3  1360  9.03e7 AGAM  Chairs         195 No old p… TRUE            http…
##  4  1783  9.03e7 AGAM  Childre…       195 No old p… TRUE            http…
##  5  1837  7.03e7 AGAM  Childre…       195 No old p… TRUE            http…
##  6  1135  5.01e7 AGEN  Chairs         245 No old p… TRUE            http…
##  7  1618  5.02e7 ALEX  Chests …       550 No old p… TRUE            http…
##  8  1631  1.02e7 ALEX  Chests …       345 No old p… TRUE            http…
##  9  1667  4.02e7 ALEX  Chests …       545 No old p… TRUE            http…
## 10  2680  2.03e7 ALEX  Tables …       200 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Wrapping desc() around character or category variable reverses the sorting:

ikea %>% 
  arrange(desc(name))
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1  1110  4.18e5 YNGV… Café fu…       399 No old p… TRUE            http…
##  2  1117  8.04e7 YNGV… Café fu…       395 No old p… TRUE            http…
##  3  1432  8.04e7 YNGV… Chairs         395 No old p… TRUE            http…
##  4  1529  4.18e5 YNGV… Chairs         399 No old p… TRUE            http…
##  5  3468  8.03e7 VUKU  Wardrob…        49 No old p… TRUE            http…
##  6  1503  7.05e7 VOLF… Chairs         175 No old p… FALSE           http…
##  7  1509  9.04e7 VOLF… Chairs         375 No old p… TRUE            http…
##  8  1517  8.04e7 VOLF… Chairs         375 No old p… TRUE            http…
##  9   134  4.04e7 VITV… Beds           200 No old p… TRUE            http…
## 10   272  9.03e7 VITT… Bookcas…       245 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

It’s also possible to sort by several variables:

ikea %>% 
  arrange(height, width, depth)
## # A tibble: 1,899 x 14
##       X1 item_id name  category price_sar old_price sellable_online link 
##    <dbl>   <dbl> <chr> <chr>        <dbl> <chr>     <lgl>           <chr>
##  1   213  2.02e7 SVÄR… Beds           300 SR 375    TRUE            http…
##  2   626  4.03e7 IVAR  Bookcas…        45 No old p… TRUE            http…
##  3   461  3.36e5 SKÅD… Bookcas…         6 SR 10/4 … TRUE            http…
##  4   616  3.40e5 EKET  Bookcas…        15 No old p… TRUE            http…
##  5   711  8.03e7 EKET  Bookcas…        20 No old p… TRUE            http…
##  6  2404  7.93e7 VALL… Sofas &…       320 SR 400    TRUE            http…
##  7   379  5.03e7 BROR  Bookcas…        15 No old p… TRUE            http…
##  8  2917  9.04e7 VIKH… Tables …       395 No old p… TRUE            http…
##  9  1716  5.04e7 NORD… Chests …       140 SR 175    TRUE            http…
## 10  2867  7.04e7 BJÖR… Tables …       395 No old p… TRUE            http…
## # … with 1,889 more rows, and 6 more variables: other_colors <chr>,
## #   description <chr>, designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Try it out

Use the penguins data for the exercises. Don’t save your changes, i.e. don’t overwrite the dataframe!

1a. Move the columns around so that “island” is the first column. 1b. Sort the columns so that all numeric ones are shown first.

2a. Show the penguins ordered by weight - first in ascending, then in descending order. 2b. Reorder the data by the island the penguins live on.

  1. How could you rename “bill_length_mm” to “beak_length” and “bill_depth_mm” to “beak_depth”?

(4) select()

Select one column

Before we move on, let’s convert “category” into a factor:

ikea$category <- as_factor(ikea$category)

We’ll show you a more elegant way of doing this next time!

The traditional syntax for dealing with columns is dataframe$column. A useful step in using pipes and tidyverse calls is the ability to select specific columns. That is, instead of writing ikea$category we can write:

ikea %>% 
  select(category) 
## # A tibble: 1,899 x 1
##    category     
##    <fct>        
##  1 Bar furniture
##  2 Bar furniture
##  3 Bar furniture
##  4 Bar furniture
##  5 Bar furniture
##  6 Bar furniture
##  7 Bar furniture
##  8 Bar furniture
##  9 Bar furniture
## 10 Bar furniture
## # … with 1,889 more rows

We can then use this column for further calculations, like piping it on to the summary call. This will provide the same result as summary(ikea$price)

ikea %>% 
  select(price_sar) %>% 
  summary()
##    price_sar   
##  Min.   :   6  
##  1st Qu.: 295  
##  Median : 680  
##  Mean   :1221  
##  3rd Qu.:1589  
##  Max.   :9585

We could, for example, look at the tallest item:

ikea %>% 
  select(height) %>% 
  max()
## [1] 301

Or the thinnest:

ikea %>% 
  select(width) %>% 
  min()
## [1] 2

Select multiple columns

You can also use select() to take multiple columns.

ikea %>% 
  select(name, price_sar, category)
## # A tibble: 1,899 x 3
##    name     price_sar category     
##    <chr>        <dbl> <fct>        
##  1 STIG            69 Bar furniture
##  2 NORBERG        225 Bar furniture
##  3 INGOLF         345 Bar furniture
##  4 FRANKLIN       129 Bar furniture
##  5 FRANKLIN       129 Bar furniture
##  6 FRANKLIN       149 Bar furniture
##  7 INGOLF         395 Bar furniture
##  8 NORRARYD       395 Bar furniture
##  9 FREKVENS       177 Bar furniture
## 10 EKEDALEN       345 Bar furniture
## # … with 1,889 more rows

You can see that these columns are presented in the order you gave them to the select call, too:

ikea %>% 
  select(category, price_sar, name)
## # A tibble: 1,899 x 3
##    category      price_sar name    
##    <fct>             <dbl> <chr>   
##  1 Bar furniture        69 STIG    
##  2 Bar furniture       225 NORBERG 
##  3 Bar furniture       345 INGOLF  
##  4 Bar furniture       129 FRANKLIN
##  5 Bar furniture       129 FRANKLIN
##  6 Bar furniture       149 FRANKLIN
##  7 Bar furniture       395 INGOLF  
##  8 Bar furniture       395 NORRARYD
##  9 Bar furniture       177 FREKVENS
## 10 Bar furniture       345 EKEDALEN
## # … with 1,889 more rows

Remove columns with select

You can also remove columns using select if you use the minus sign. For example, here, we have the first column (“X1”) which is a sort of row numbering. If you don’t want this column, you can drop it with select:

ikea %>% 
  select(-X1)
## # A tibble: 1,899 x 13
##    item_id name  category price_sar old_price sellable_online link  other_colors
##      <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
##  1  8.02e7 STIG  Bar fur…        69 No old p… TRUE            http… Yes         
##  2  3.02e7 NORB… Bar fur…       225 No old p… TRUE            http… No          
##  3  1.01e7 INGO… Bar fur…       345 No old p… TRUE            http… No          
##  4  7.04e7 FRAN… Bar fur…       129 No old p… TRUE            http… No          
##  5  5.04e7 FRAN… Bar fur…       129 No old p… TRUE            http… No          
##  6  9.04e7 FRAN… Bar fur…       149 No old p… TRUE            http… No          
##  7  1.22e5 INGO… Bar fur…       395 No old p… TRUE            http… No          
##  8  3.98e5 NORR… Bar fur…       395 No old p… TRUE            http… No          
##  9  5.04e7 FREK… Bar fur…       177 SR 295    TRUE            http… No          
## 10  4.01e5 EKED… Bar fur…       345 No old p… TRUE            http… No          
## # … with 1,889 more rows, and 5 more variables: description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>

You can also remove multiple columns at once by writing them in an array c().

ikea %>% 
  select(-c(X1, old_price))
## # A tibble: 1,899 x 12
##    item_id name  category price_sar sellable_online link  other_colors
##      <dbl> <chr> <fct>        <dbl> <lgl>           <chr> <chr>       
##  1  8.02e7 STIG  Bar fur…        69 TRUE            http… Yes         
##  2  3.02e7 NORB… Bar fur…       225 TRUE            http… No          
##  3  1.01e7 INGO… Bar fur…       345 TRUE            http… No          
##  4  7.04e7 FRAN… Bar fur…       129 TRUE            http… No          
##  5  5.04e7 FRAN… Bar fur…       129 TRUE            http… No          
##  6  9.04e7 FRAN… Bar fur…       149 TRUE            http… No          
##  7  1.22e5 INGO… Bar fur…       395 TRUE            http… No          
##  8  3.98e5 NORR… Bar fur…       395 TRUE            http… No          
##  9  5.04e7 FREK… Bar fur…       177 TRUE            http… No          
## 10  4.01e5 EKED… Bar fur…       345 TRUE            http… No          
## # … with 1,889 more rows, and 5 more variables: description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Once your preview looks the way you want it –just make sure to save your results by committing it to a variable (over the old one is fine).

(ikea <- ikea %>% 
  select(-X1))
## # A tibble: 1,899 x 13
##    item_id name  category price_sar old_price sellable_online link  other_colors
##      <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
##  1  8.02e7 STIG  Bar fur…        69 No old p… TRUE            http… Yes         
##  2  3.02e7 NORB… Bar fur…       225 No old p… TRUE            http… No          
##  3  1.01e7 INGO… Bar fur…       345 No old p… TRUE            http… No          
##  4  7.04e7 FRAN… Bar fur…       129 No old p… TRUE            http… No          
##  5  5.04e7 FRAN… Bar fur…       129 No old p… TRUE            http… No          
##  6  9.04e7 FRAN… Bar fur…       149 No old p… TRUE            http… No          
##  7  1.22e5 INGO… Bar fur…       395 No old p… TRUE            http… No          
##  8  3.98e5 NORR… Bar fur…       395 No old p… TRUE            http… No          
##  9  5.04e7 FREK… Bar fur…       177 SR 295    TRUE            http… No          
## 10  4.01e5 EKED… Bar fur…       345 No old p… TRUE            http… No          
## # … with 1,889 more rows, and 5 more variables: description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Leveling up select()

Until now, we’ve used select() in combination with the full column name, but there are helper functions that let you select columns based on other criteria.

For example, here’s how we can select all columns that end with “e” - by specifying ends_with("e") in the select() call:

ikea %>% 
  select(ends_with("e"))
## # A tibble: 1,899 x 3
##    name     old_price    sellable_online
##    <chr>    <chr>        <lgl>          
##  1 STIG     No old price TRUE           
##  2 NORBERG  No old price TRUE           
##  3 INGOLF   No old price TRUE           
##  4 FRANKLIN No old price TRUE           
##  5 FRANKLIN No old price TRUE           
##  6 FRANKLIN No old price TRUE           
##  7 INGOLF   No old price TRUE           
##  8 NORRARYD No old price TRUE           
##  9 FREKVENS SR 295       TRUE           
## 10 EKEDALEN No old price TRUE           
## # … with 1,889 more rows

The opposite is also possible, e.g. to return all columns that start with “des”:

ikea %>% 
  select(starts_with("des"))
## # A tibble: 1,899 x 2
##    description                                         designer            
##    <chr>                                               <chr>               
##  1 Bar stool with backrest,          74 cm             Henrik Preutz       
##  2 Wall-mounted drop-leaf table,          74x60 cm     Marcus Arvonen      
##  3 Bar stool with backrest,          63 cm             Carina Bengs        
##  4 Bar stool with backrest, foldable,          63 cm   K Hagberg/M Hagberg 
##  5 Bar stool with backrest, foldable,          63 cm   K Hagberg/M Hagberg 
##  6 Bar stool with backrest, foldable,          74 cm   K Hagberg/M Hagberg 
##  7 Bar stool with backrest,          74 cm             Carina Bengs        
##  8 Bar stool with backrest,          74 cm             Nike Karlsson       
##  9 Bar stool with backrest, in/outdoor,          74 cm Nicholai Wiig Hansen
## 10 Bar stool with backrest,          75 cm             Ehlén Johansson     
## # … with 1,889 more rows

contains is another helper function. Here, we’re using it to show all columns that contain an underscore:

ikea %>% 
  select(contains("_"))
## # A tibble: 1,899 x 5
##     item_id price_sar old_price    sellable_online other_colors
##       <dbl>     <dbl> <chr>        <lgl>           <chr>       
##  1 80155205        69 No old price TRUE            Yes         
##  2 30180504       225 No old price TRUE            No          
##  3 10122647       345 No old price TRUE            No          
##  4 70404875       129 No old price TRUE            No          
##  5 50406465       129 No old price TRUE            No          
##  6 90404879       149 No old price TRUE            No          
##  7   121766       395 No old price TRUE            No          
##  8   397736       395 No old price TRUE            No          
##  9 50420329       177 SR 295       TRUE            No          
## 10   400550       345 No old price TRUE            No          
## # … with 1,889 more rows

We can also select a range of variables using a colon. This works both with variables and (a range of) numbers:

ikea %>% 
  select(name:category)
## # A tibble: 1,899 x 2
##    name     category     
##    <chr>    <fct>        
##  1 STIG     Bar furniture
##  2 NORBERG  Bar furniture
##  3 INGOLF   Bar furniture
##  4 FRANKLIN Bar furniture
##  5 FRANKLIN Bar furniture
##  6 FRANKLIN Bar furniture
##  7 INGOLF   Bar furniture
##  8 NORRARYD Bar furniture
##  9 FREKVENS Bar furniture
## 10 EKEDALEN Bar furniture
## # … with 1,889 more rows
ikea %>% 
  select(1:3) # first three columns
## # A tibble: 1,899 x 3
##     item_id name     category     
##       <dbl> <chr>    <fct>        
##  1 80155205 STIG     Bar furniture
##  2 30180504 NORBERG  Bar furniture
##  3 10122647 INGOLF   Bar furniture
##  4 70404875 FRANKLIN Bar furniture
##  5 50406465 FRANKLIN Bar furniture
##  6 90404879 FRANKLIN Bar furniture
##  7   121766 INGOLF   Bar furniture
##  8   397736 NORRARYD Bar furniture
##  9 50420329 FREKVENS Bar furniture
## 10   400550 EKEDALEN Bar furniture
## # … with 1,889 more rows

Here, the order of the columns matters!

Other helper functions are: - matches: similar to contains, but can use regular expressions - num_range: in a dataset with the variables X1, X2, X3, X4, Y1, and Y2, select(num_range(“X”, 1:3)) returns X1, X2, and X3

Try it out

  1. In the penguins data, only show the species and bill length columns (preview only!).

  2. Remove the year column. This time, make sure to save the change.

Select all columns that 3. end with "_mm" 4. contain “length” 5. start with “bill”

  1. Select the columns from bill length to flipper length.

(5) filter()

Filter Use filter to select rows that meet a condition.

You can use: - equals to: == - not equal to: != - greater than: > - greater than or equal to: >= - less than: < - less than or equal to: <= - in (i.e. in an array): %in%

ikea %>% 
  filter(price_sar > 8500)
## # A tibble: 3 x 13
##   item_id name  category price_sar old_price sellable_online link  other_colors
##     <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
## 1  2.93e7 LIDH… Beds          9585 No old p… TRUE            http… Yes         
## 2  7.93e7 LIDH… Sofas &…      9585 No old p… TRUE            http… Yes         
## 3  8.93e7 GRÖN… Sofas &…      8900 No old p… TRUE            http… No          
## # … with 5 more variables: description <chr>, designer <chr>, depth <dbl>,
## #   height <dbl>, width <dbl>

You can also select items with a specific price:

ikea %>% 
  filter(price_sar == 265)
## # A tibble: 1 x 13
##   item_id name  category price_sar old_price sellable_online link  other_colors
##     <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
## 1  2.93e7 EKET  Bookcas…       265 No old p… TRUE            http… Yes         
## # … with 5 more variables: description <chr>, designer <chr>, depth <dbl>,
## #   height <dbl>, width <dbl>

Or you can use it to select all items in a given category. Notice here that category is a factor column, so you have to use quotation marks (same applies for characters).

Look at the error below:

# ikea %>% 
#   filter(category == Beds)

The correct syntax is: (because you’re matching to a string)

ikea %>% 
  filter(category == "Beds")
## # A tibble: 78 x 13
##    item_id name  category price_sar old_price sellable_online link  other_colors
##      <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
##  1  4.93e7 BRIM… Beds          895  SR 925    TRUE            http… No          
##  2  8.93e7 PLAT… Beds         2111  SR 2,205  TRUE            http… No          
##  3  5.05e7 VATT… Beds          995  No old p… TRUE            http… No          
##  4  2.04e7 BRIM… Beds          575  No old p… TRUE            http… No          
##  5  1.92e7 MALM  Beds          920  No old p… TRUE            http… Yes         
##  6  7.99e7 BRIM… Beds          575  No old p… TRUE            http… Yes         
##  7  9.03e7 HEMN… Beds         1495  No old p… TRUE            http… No          
##  8  7.90e7 MALM  Beds          670  No old p… TRUE            http… Yes         
##  9  8.93e7 PLAT… Beds         2600. SR 2,880  TRUE            http… No          
## 10  9.04e7 HAMM… Beds          399  No old p… TRUE            http… No          
## # … with 68 more rows, and 5 more variables: description <chr>, designer <chr>,
## #   depth <dbl>, height <dbl>, width <dbl>

Make sure to spell this exactly as it is spelled in the data, i.e. with a capital B!

To use %in%, give an array of options (formatted in the correct way based on whether the column is a character or numeric):

ikea %>% 
  filter(name %in% c("BRIMNES", "BILLY", "KALLAX"))
## # A tibble: 85 x 13
##    item_id name  category price_sar old_price sellable_online link  other_colors
##      <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
##  1  4.93e7 BRIM… Beds           895 SR 925    TRUE            http… No          
##  2  2.04e7 BRIM… Beds           575 No old p… TRUE            http… No          
##  3  7.99e7 BRIM… Beds           575 No old p… TRUE            http… Yes         
##  4  2.02e7 BRIM… Beds           220 No old p… TRUE            http… Yes         
##  5  2.29e5 BRIM… Beds          1095 No old p… TRUE            http… No          
##  6  4.01e5 BRIM… Beds           220 SR 250    TRUE            http… No          
##  7  1.91e7 BRIM… Beds          1795 No old p… TRUE            http… Yes         
##  8  2.03e7 KALL… Bookcas…       115 No old p… TRUE            http… Yes         
##  9  8.03e7 KALL… Bookcas…       250 No old p… TRUE            http… Yes         
## 10  2.03e7 KALL… Bookcas…        30 SR 50     TRUE            http… No          
## # … with 75 more rows, and 5 more variables: description <chr>, designer <chr>,
## #   depth <dbl>, height <dbl>, width <dbl>

Note that filter is case-sensitive, so capitals matter.

Leveling up filter()

You can use filter() to match rows by as many criteria as you like using logical operators: - & “and” - | “or”

For example, to see beds which are available in other colours:

ikea %>% 
  filter(category == "Beds" & other_colors == "Yes")
## # A tibble: 48 x 13
##    item_id name  category price_sar old_price sellable_online link  other_colors
##      <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
##  1  1.92e7 MALM  Beds           920 No old p… TRUE            http… Yes         
##  2  7.99e7 BRIM… Beds           575 No old p… TRUE            http… Yes         
##  3  7.90e7 MALM  Beds           670 No old p… TRUE            http… Yes         
##  4  9.24e6 NORD… Beds          2290 No old p… TRUE            http… Yes         
##  5  6.92e7 SONG… Beds           570 No old p… TRUE            http… Yes         
##  6  9.31e6 NYHA… Beds          1470 No old p… TRUE            http… Yes         
##  7  2.02e7 BRIM… Beds           220 No old p… TRUE            http… Yes         
##  8  9.19e6 HEMN… Beds          2185 No old p… TRUE            http… Yes         
##  9  4.03e7 NORD… Beds          1595 No old p… TRUE            http… Yes         
## 10  3.93e7 VALL… Beds          1848 SR 2,310  TRUE            http… Yes         
## # … with 38 more rows, and 5 more variables: description <chr>, designer <chr>,
## #   depth <dbl>, height <dbl>, width <dbl>

…or tables, desks, and chairs (again, taking care to match the spelling of the data frame exactly) that each cost less than 1000 rials:

ikea %>% 
  filter(category %in% c("Chairs", "Tables & desks") & price_sar < 1000)
## # A tibble: 269 x 13
##    item_id name  category price_sar old_price sellable_online link  other_colors
##      <dbl> <chr> <fct>        <dbl> <chr>     <lgl>           <chr> <chr>       
##  1  4.05e7 BING… Chairs         595 No old p… TRUE            http… Yes         
##  2  4.05e7 SKRU… Chairs         545 No old p… TRUE            http… Yes         
##  3  2.05e7 STRA… Chairs         995 No old p… TRUE            http… Yes         
##  4  5.01e7 PELLO Chairs         195 No old p… TRUE            http… No          
##  5  5.04e7 NILS… Chairs         395 No old p… TRUE            http… No          
##  6  5.01e7 AGEN  Chairs         245 No old p… TRUE            http… No          
##  7  1.02e7 ADDE  Chairs          40 No old p… TRUE            http… Yes         
##  8  6.02e7 GUNDE Chairs          30 No old p… TRUE            http… No          
##  9  1.02e7 NOLM… Chairs         175 No old p… TRUE            http… Yes         
## 10  7.04e7 STRA… Chairs         495 No old p… TRUE            http… No          
## # … with 259 more rows, and 5 more variables: description <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>

One additional option for filter is to find NAs (is.na()) or exclude NAs (!is.na()). We’ve already removed all NAs from the ikea data but we can show this with the penguins data. Let’s say we’d like to select body mass, then call min() to see the smallest value:

penguins %>% 
  select(body_mass_g) %>% 
  min()
## [1] NA

This gives us an NA because some penguins apparently refused to be weighed =) We can first remove NAs from this column and then try the command again:

penguins %>% 
  filter(!is.na(body_mass_g)) %>% #could also use drop_na(body_mass_g)
  select(body_mass_g) %>% 
  min()
## [1] 2700

Try it out

  1. How many items in this dataset were designed by Carina Bengs? How many of them are cupboards or cabinets?

  2. Find all wardrobes, trolleys, and chairs.

  3. Show only items that are smaller than 50 cm in depth, height, and width. How could you figure out which categories they belong to?

(6) Separate

Read in the ikea_raw file. This is how the data was first entered by an intern who doesn’t know about tidy data because this data is not tidy. Have a look at the data and try to figure out why not. Hint: there are two problematic columns. Compare this data to the data we’ve been working with so far to find them.

ikea_raw <- read_csv("data/ikea_raw.csv")
## Parsed with column specification:
## cols(
##   id_name = col_character(),
##   category = col_character(),
##   price_sar = col_double(),
##   old_price = col_character(),
##   sellable_online = col_logical(),
##   link = col_character(),
##   other_colors = col_character(),
##   description = col_character(),
##   designer = col_character(),
##   dimensions = col_character()
## )
head(ikea_raw)
## # A tibble: 6 x 10
##   id_name category price_sar old_price sellable_online link  other_colors
##   <chr>   <chr>        <dbl> <chr>     <lgl>           <chr> <chr>       
## 1 801552… Bar fur…        69 No old p… TRUE            http… Yes         
## 2 301805… Bar fur…       225 No old p… TRUE            http… No          
## 3 101226… Bar fur…       345 No old p… TRUE            http… No          
## 4 704048… Bar fur…       129 No old p… TRUE            http… No          
## 5 504064… Bar fur…       129 No old p… TRUE            http… No          
## 6 904048… Bar fur…       149 No old p… TRUE            http… No          
## # … with 3 more variables: description <chr>, designer <chr>, dimensions <chr>

The issues are that, instead of two separate columns for id and item name, we have “id_name”, and instead of three separate columns per dimension there’s one column called “dimensions”. So the data is not tidy because not every variable is stored in its own column. We can fix that using separate(). It takes the following arguments: - data: our dataframe, we’ll pipe it - col: which column needs to be separated - into: a vector that contains the names of the new columns - sep: which symbol separates the values - remove (optional): by default, the original column will be deleted. Set remove to FALSE to keep it.

To do that for the dimensions columns, we need to specify the column that should be changed (“dimension”), list the three columns we want the data to be separated into, and tell R which symbol is used to separate the values. Here, it’s an “x”.

(ikea_raw <- ikea_raw %>% 
  separate(col = dimensions,
           into = c("depth", "height", "width"),
           sep = "x"))
## # A tibble: 1,899 x 12
##    id_name category price_sar old_price sellable_online link  other_colors
##    <chr>   <chr>        <dbl> <chr>     <lgl>           <chr> <chr>       
##  1 801552… Bar fur…        69 No old p… TRUE            http… Yes         
##  2 301805… Bar fur…       225 No old p… TRUE            http… No          
##  3 101226… Bar fur…       345 No old p… TRUE            http… No          
##  4 704048… Bar fur…       129 No old p… TRUE            http… No          
##  5 504064… Bar fur…       129 No old p… TRUE            http… No          
##  6 904048… Bar fur…       149 No old p… TRUE            http… No          
##  7 121766… Bar fur…       395 No old p… TRUE            http… No          
##  8 397736… Bar fur…       395 No old p… TRUE            http… No          
##  9 504203… Bar fur…       177 SR 295    TRUE            http… No          
## 10 400550… Bar fur…       345 No old p… TRUE            http… No          
## # … with 1,889 more rows, and 5 more variables: description <chr>,
## #   designer <chr>, depth <chr>, height <chr>, width <chr>

Try it out

Fix the “id_name” column: Separate it into “item_id” and “name”.

(7) Unite

The opposite of separate(). This lets you glue columns together. - col is the name of the new column - the next argument, a vector, lists the columns that should be united - sep, as above, lets you specify how the values should be separated. - remove (optional): by default, the original column will be deleted. Set remove to FALSE to keep it.

This is useful if one variable is spread across two or more columns. For example, if year is spread out into two columns, century and decade (e.g. 19 in one column, 64 in another), you could use unite() to glue these values together into one “year” column.

Here, let’s use unite() to expand on the descriptions. Specifically, we’ll want a column that contains the item name followed by a colon and a space and then the description. This new column should be called “long_description” and contain the name and description columns, separated by “:”.

ikea %>% 
  unite(col = long_description,
        c("name", "description"),
        sep = ": ")
## # A tibble: 1,899 x 12
##    item_id long_description category price_sar old_price sellable_online link 
##      <dbl> <chr>            <fct>        <dbl> <chr>     <lgl>           <chr>
##  1  8.02e7 STIG: Bar stool… Bar fur…        69 No old p… TRUE            http…
##  2  3.02e7 NORBERG: Wall-m… Bar fur…       225 No old p… TRUE            http…
##  3  1.01e7 INGOLF: Bar sto… Bar fur…       345 No old p… TRUE            http…
##  4  7.04e7 FRANKLIN: Bar s… Bar fur…       129 No old p… TRUE            http…
##  5  5.04e7 FRANKLIN: Bar s… Bar fur…       129 No old p… TRUE            http…
##  6  9.04e7 FRANKLIN: Bar s… Bar fur…       149 No old p… TRUE            http…
##  7  1.22e5 INGOLF: Bar sto… Bar fur…       395 No old p… TRUE            http…
##  8  3.98e5 NORRARYD: Bar s… Bar fur…       395 No old p… TRUE            http…
##  9  5.04e7 FREKVENS: Bar s… Bar fur…       177 SR 295    TRUE            http…
## 10  4.01e5 EKEDALEN: Bar s… Bar fur…       345 No old p… TRUE            http…
## # … with 1,889 more rows, and 5 more variables: other_colors <chr>,
## #   designer <chr>, depth <dbl>, height <dbl>, width <dbl>

Try it out

Expand the code above so the format is: name: description. Designed by designer. Hint: Copy the code from above, then pipe it into a new unite() statement.

Next time

  • Creating new columns and changing existing ones
    • …based on conditions (if-else statements)
  • Creating summary tables (by groups)
  • Joining dataframes